package nowcoder.hw.hj68;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        String ns = bufferedReader.readLine();
        String sort = bufferedReader.readLine();
        String score = null;
        Integer n = Integer.valueOf(ns);
        Score[] scores = new Score[n];
        for (int i = 0; i < n; i++) {
            score = bufferedReader.readLine();
            String str[] = score.split(" ");
            scores[i] = new Score(Integer.valueOf(str[1]), str[0]);
        }
        scores = mySort(scores, sort);
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < scores.length; i++) {
            stringBuilder.append(scores[i]).append("\n");
        }
        stringBuilder.deleteCharAt(stringBuilder.length() - 1);
        System.out.println(stringBuilder);

    }

    private static Score[] mySort(Score[] scores, String sort) {
        boolean down = sort.equals("0");
        return merge(scores, 0, scores.length - 1, down);
    }

    private static Score[] merge(Score[] scores, int l, int r, boolean f) {
        if (l == r) return new Score[]{scores[l]};
        int mid = (l + r) / 2;
        Score[] left = merge(scores, l, mid, f);
        Score[] right = merge(scores, mid + 1, r, f);
        Score[] sortedArr = new Score[r - l + 1];
        int i = 0, j = 0, m = 0;
        if (f) {
            while (i < left.length && j < right.length) {
                sortedArr[m++] = left[i].score >= right[j].score ? left[i++] : right[j++];
            }
        }else {
            while (i < left.length && j < right.length) {
                sortedArr[m++] = left[i].score <= right[j].score ? left[i++] : right[j++];
            }
        }

        while (i < left.length) {
            sortedArr[m++] = left[i++];
        }
        while (j < right.length) {
            sortedArr[m++] = right[j++];
        }
        return sortedArr;
    }
}

class Score {
    int score;
    String name;

    public Score(int score, String name) {
        this.score = score;
        this.name = name;
    }

    @Override
    public String toString() {
        return name + " " + score;
    }
}